<?php
/**
 * 频道控制层基类。集频道、一级二级分类、商品搜索于一身。
 * 
 * @copyright 	Copyright (c) 2011 thinkapk.com All rights reserved.
 * @package 	ThinkAPK_Action
 * @link 		http://www.thinkapk.com/
 * @author 		richie <richbossman@163.com>
 * @version 	$Id: List.class.php 7638 2011-06-04 07:17:31Z richie $
 * 
 */
class ThinkAPK_Action_List extends ThinkAPK_Action_Mall {
	//当前分类ID
	public $catId;
	//当前分类 的所有子类ID
	private $cats;
	//参数
	private $options;
	//品牌ID
	private $brandId;
	//分类信息
	private $category;
	//URL参数
	private $grade;
	//排序的字段
	private $sort = array('add_time', 'shop_price', 'last_update', 'click_count');
	//查询条件
	private $where;
	//扩展分类ID
	private $extensionGoodsId;
	//推荐的字段
	private $recommend = array('best', 'new', 'hot', 'promote');
	//推荐字段对应标题
	private $retitle = array('best'=>'精品推荐', 'new'=>'新品上架', 'hot'=>'热销商品', 'promote'=>'特惠商品');
	
	//公共赋值模块
	public function globalAssign($id){
		//初始化参数
		$this->catId = $id;
		
		//搜索页
		if(empty($this->catId)){
			$this->setParams(); // 参数
			//搜索标题
			if(!empty($this->options['recommend']) && in_array($this->options['recommend'], $this->recommend)){
				$title = $this->retitle[$this->options['recommend']];
				$this->assign('navshow', $this->options['recommend']);
			}elseif($this->options['keyword'] != ''){
				$title = $this->options['keyword'];
			}else{
				$title = '全部商品';
			}
			$this->setTitle($title);
			$this->setKeywords($title);
			$this->setPosition(0, $title);
			$this->setCondition(); //筛选条件
			$this->setQueryCondition(); //
			$total = $this->getCategoryGoodsCount();
			$pageshow = P($total, $this->options['qty'], '', array('url'=>$this->setUrl(array('page'=>'%page%'))));
			$minpageshow = P($total, $this->options['qty'], '', array('url'=>$this->setUrl(array('page'=>'%page%'))), 'prev-next');
			$this->assign('pageshow', $pageshow);
			$this->assign('minpageshow', $minpageshow);
			$goods_list = $this->getCategoryGoodsList();
			$this->assign('goods_list', $goods_list); 
			$list = D('SalesTop')->get();//销售排行
    		$this->assign('SalesTopList', $list);
		//分类列表页显示
		}else{
			$this->category = D('Category')->find($this->catId);
			if(empty($this->category)){
				$this->error('');
			}
			$level = D('Category')->getLevel($this->catId);
			//设置页面参数
			$this->setTitle(!empty($this->category['custom_title']) ? $this->category['custom_title'] : $this->category['cat_name']);
			$this->setKeywords($this->category['keywords']);
			$this->setDescription($this->category['cat_desc']);
			$this->setPosition($id);
			//设置参数
			if($level != 1){
				$this->setParams(); // 参数
				$this->setCondition(); //筛选条件
				$this->setQueryCondition(); //查询条件
				//
				
				$total = $this->getCategoryGoodsCount();
				$pageshow = P($total, $this->options['qty'], '', array('url'=>$this->setUrl(array('page'=>'%page%'))));
				$minpageshow = P($total, $this->options['qty'], '', array('url'=>$this->setUrl(array('page'=>'%page%'))), 'prev-next');
				$this->assign('pageshow', $pageshow);
				$this->assign('minpageshow', $minpageshow);
				$goods_list = $this->getCategoryGoodsList();
				$this->assign('goods_list', $goods_list);
			}
			//一级分类
			if($level == 1){
				$this->assign('topflash', D('RelationImg')->get('cate-top-ad', $this->catId));
				$this->assign('imgad', D('RelationImg')->get('cate-scroll-ad', $this->catId));
				$this->assign('gitem', $this->listRecommendModule($this->catId));
				$this->assign('list_module', $this->getModule($this->catId));
			//二级分类
			}elseif($level == 2){
				$this->assign('topflash', D('RelationImg')->get('cate-top-ad', $this->catId));
			//三级分类
			}elseif($level == 3){
				$this->assign('gitem', $this->listRecommendModule($this->catId));
			}
			
			//传值
			$this->assign('cat_id', $this->catId);
			$this->assign('categoryinfo', $this->category);
			$this->assign('level', $level);
			//左边导航
			$this->setLeftCategory($id);
		}
		$this->assign('list_right_custom', $this->getModuleCustomContent('list-right-custom',$this->catId));
		$list_left_custom = $this->getModuleCustomContent('list-left-custom', $this->catId); 
		$this->assign('list_left_custom', $list_left_custom); 
		$this->assign('notice', D('Article')->getNotice(5)); // 实惠公告
		$list  = D('SalesTop')->get('makeselltop',$this->catId);
		$this->assign('makeselltop',$list );//热销排行 
		$this->assign('layout', $this->setLayout()); // 布局方式
		$this->assign('qty', $this->setQty()); // 列表显示数量
		$this->assign('sort_order', $this->setSortOrder()); // 排序
		$this->assign('options', $this->options); 
	}
 
	
	//列表推荐商品，一级分类
	public function listRecommendModule($id){
		$module = D('Module')->getAllModule('list', true, $id);
		foreach($module as $key=>$mod){
			$module[$key]['goods'] = D('RelationGoods')->get('list-recommend', $mod['id']);
		}
		return $module;
	}
	
	//取得固定的自定义模块的内容
	public function getModuleCustomContent($type, $id){
		if($id){
		   $moduleId = D('Module')->where(array('type'=>$type, 'pid'=>$id))->getField('id');	
		}else{
    	   $moduleId = D('Module')->where(array('type'=>$type, 'pid'=>'0'))->getField('id');
		} 
    	$result = D('ModuleContent')->where('module_id='.$moduleId)->limit(1)->getField('content');
    	//echo '<hr>'.D()->getLastSql(); 
    	return $result;
	}
	
	//一级分类的模块列表
	public function getModule($id){
		$D = D('Module');
		//后台需要显示所有模块
		if(APP_NAME == 'admin'){
			$module = $D->getAllModule('list-module', true, $id);
			$module = $this->getListModuleData($module);
		}else{
			$module = $D->getAllModule('list-module', false, $id);
			$module = $this->getListModuleData($module);
		}
		return $module;
	}
	
	//取得一级分类模块的数据
	private function getListModuleData($module=array()){
		foreach($module as $key=>$mod){
			//功能模块
			if($mod['module_type'] == 'function_module'){
				if($mod['show_title']){
					$module[$key]['titles'] = D('RelationText')->get('list-module-titles', $mod['id']);
				}
				$left = D('RelationImg')->get('left-module-ad', $mod['id']);
				if(!empty($left)) $module[$key]['left'] = $left;
				$right = D('RelationGoods')->get('list-module-goods', $mod['id']);
				if(!empty($right)) $module[$key]['right'] = $right; 
			//图片广告
			}elseif ($mod['module_type'] == 'ad_module'){
				$ad = D('RelationImg')->get('list-module-ad', $mod['id']);
				if(!empty($ad)) $module[$key]['ad'] = $ad;
			//自定义内容
			}elseif($mod['module_type'] == 'custom_module'){
				$module[$key]['content'] = D('ModuleContent')->where(array('module_id'=>$mod['id']))->getField('content');
			}
		}
		return $module;
	}
	
	//取得查询筛选条件所需要的查询条件
	private function getConditionForFitler(){
		$map = ' is_delete=0 AND is_on_sale=1 ';
		if($this->catId){
			if($this->cats){
				$map .= " AND (".D('Goods')->dbIn($this->cats, 'cat_id')." OR ".D('Goods')->dbIn($this->extensionGoodsId, 'goods_id').")";
			}
		}elseif($this->options['recommend']){
			$map .= 'AND is_'.$this->options['recommend'].'=1 ';
		}elseif($this->options['keyword'] != ''){
			$map .= " AND (goods_name LIKE '%".$this->options['keyword']."%' OR goods_maidian LIKE '%".$this->options['keyword']."%' OR keywords LIKE '".$this->options['keyword']."')";
		}
		return $map;
	}
	
	//取得分类下品牌列表
	private function getCategoryBrand(){
		$brands = D('Goods')->getBrandIdByCatId($this->getConditionForFitler());
		$brand = D('Brand')->getBrandForList($brands);
		$bd = array();
		if($brand){
			$bd[0]['bid']=0;
			$bd[0]['name']='全部';
			if(!$this->brandId){
				$bd[0]['select'] = 1;
			}
			$bd[0]['url'] = $this->setUrl(array('bid'=>0, 'page'=>1));
		}
		foreach ($brand as $bid=>$name){
			$bd[$bid]['bid'] = $bid;
			$bd[$bid]['name'] = $name;
			if($this->brandId == $bid){
				$bd[$bid]['select'] = 1;
			}
			$bd[$bid]['url'] = $this->setUrl(array('bid'=>$bid, 'page'=>1));
		}
		return $bd;
	}
	
	/**
	 * 取得价格分级数组
	 *
	 * @param array $price
	 * @return array
	 */
	private function getPriceGrade(){
		$price = D('Goods')->getMinAndMaxPrice($this->getConditionForFitler());
		if(empty($price['min']) && empty($price['max'])) return 0;
		$price['min'] = 1;
		if($price['max'] >= 5000){
			$grade = 2000;
		}elseif($price['max'] >= 3000 && $price['max'] < 5000){
			$grade = 1000;
		}elseif($price['max'] >= 1000 && $price['max'] < 3000){
			$grade = 500;
		}elseif($price['max'] >= 500 && $price['max'] < 1000){
			$grade = 200;
		}elseif($price['max'] >= 200 && $price['max'] < 500){
			$grade = 100;
		}elseif($price['max'] >= 50 && $price['max'] < 200){
			$grade = 50;
		}elseif($price['max'] < 50){
			$grade = 20;
		}
		$gradeArray = array();
		$level = ceil($price['max']/$grade);
		if($level){
			$gradeArray[0]['min']=0;
			$gradeArray[0]['max']=0;
			$gradeArray[0]['name'] = '全部';
			if($this->options['min'] == 0 && $this->options['max'] == 0){
				$gradeArray[0]['select'] = 1;
			}
			$gradeArray[0]['url'] = $this->setUrl(array('min'=>0, 'max'=>0, 'page'=>1));
		}
		for($i=1; $i<=$level; $i++){
			$gradeArray[$i]['min'] = $price['min'] - 1;
			$gradeArray[$i]['max'] = $price['min'] + $grade - 2;
			$price['min'] = $price['min'] + $grade;
			$gradeArray[$i]['name'] = $gradeArray[$i]['min'].'-'.$gradeArray[$i]['max'];
			if($this->options['min'] == $gradeArray[$i]['min'] && $this->options['max'] == $gradeArray[$i]['max']){
				$gradeArray[$i]['select'] = 1;
			}
			$gradeArray[$i]['url'] = $this->setUrl(array('min'=>$gradeArray[$i]['min'], 'max'=>$gradeArray[$i]['max'], 'page'=>1));
		}
		return $gradeArray;
	}
	
	//取得关联的扩展属性
	private function getFilterAttr(){
		if(empty($this->category['filter_attr'])){
			//如果当前分类的关联属性为空，取上一级的关联属性
			//$this->category['filter_attr'] = M()->where('cat_id='.$this->category['parent_id'])->getField('filter_attr');
			//if(empty($this->category['filter_attr'])){
			//	return array();
			//}
			return array();
		}
		$cat_filter['filter_attr'] = explode('.', $this->options['attr']);
		$cat_filter_attr = explode(',', $this->category['filter_attr']);
		foreach($cat_filter_attr as $key=>$value){
			$temp_name = M()->table(C('DB_PREFIX').'attribute as a,'.C('DB_PREFIX').'goods_attr AS g')
							->where("a.attr_id=g.attr_id AND a.attr_id=$value")
							->getField('a.attr_name');
			//如果存在该属性的商品
			if($temp_name){
				$all_attr_list[$key]['name'] = $temp_name;
                $attr_list = M()->field('a.attr_id, MIN(a.goods_attr_id ) AS goods_id, a.attr_value AS attr_value')
                			->table(C('DB_PREFIX').'goods_attr as a')
                			->where(" a.attr_id='$value'")
                			->group('a.attr_value')
                			->findAll();
                $temp_arrt_url_arr = array();

                for ($i = 0; $i < count($cat_filter_attr); $i++)        //获取当前url中已选择属性的值，并保留在数组中
                {
                    $temp_arrt_url_arr[$i] = !empty($cat_filter['filter_attr'][$i]) ? $cat_filter['filter_attr'][$i] : 0;
                }

                $temp_arrt_url_arr[$key] = 0;                           //“全部”的信息生成
                $temp_arrt_url = implode('.', $temp_arrt_url_arr);
                $all_attr_list[$key]['attr_list'][0]['name'] = '全部';
                $all_attr_list[$key]['attr_list'][0]['url'] = $this->setUrl(array('attr'=>$temp_arrt_url, 'page'=>1));
                $all_attr_list[$key]['attr_list'][0]['select'] = empty($cat_filter['filter_attr'][$key]) ? 1 : 0;

                foreach ($attr_list as $k => $v)
                {
                    $temp_key = $k + 1;
                    $temp_arrt_url_arr[$key] = $v['goods_id'];       //为url中代表当前筛选属性的位置变量赋值,并生成以‘.’分隔的筛选属性字符串
                    $temp_arrt_url = implode('.', $temp_arrt_url_arr);

                    $all_attr_list[$key]['attr_list'][$temp_key]['name'] = $v['attr_value'];
                    $all_attr_list[$key]['attr_list'][$temp_key]['url'] = $this->setUrl(array('attr'=>$temp_arrt_url, 'page'=>1));

                    if (!empty($cat_filter['filter_attr']) && in_array($v['goods_id'], $cat_filter['filter_attr']))
                    {
                        $all_attr_list[$key]['attr_list'][$temp_key]['select'] = 1;
                    }
                    else
                    {
                        $all_attr_list[$key]['attr_list'][$temp_key]['select'] = 0;
                    }
                }
			}
		}
		return $all_attr_list;
	}
	
	//商品扩展属性查询条件
	function getGoodsExt(){
		$ext = '';
		$filter_attr = explode(".", $this->options['attr']);
		$cat_filter_attr = explode(',', $this->category['filter_attr']);
		if (!empty($filter_attr))
        {
            $ext_group_goods = array();

            foreach ($filter_attr AS $k => $v)
            {
                if (is_numeric($v) && $v != 0 )
                {
                	$ext_group_goods = M()->table(C('DB_PREFIX').'goods_attr AS a,'.C('DB_PREFIX').'goods_attr AS b')
                		->field('DISTINCT(b.goods_id) AS id')
                		->where("b.attr_value = a.attr_value AND b.attr_id = " . $cat_filter_attr[$k] ." AND a.goods_attr_id = " . $v)
                		->findAll();
                	$exts = array();
                	foreach ($ext_group_goods as $ks){
                		$exts[] = $ks['id'];
                	}
                    $ext .= ' AND ' . D('Goods')->dbIn($exts, 'g.goods_id');
                }
            }
        }
        return $ext;
	}
	
	//设置参数
	private function setParams(){
		//当前分类的子类ID
		$this->cats =  (!empty($this->catId)) ? D('Category')->getChiledrenId($this->catId, false) : array();
		//URL扩展参数
		$this->grade = isset($_REQUEST['grade']) ? trim($_REQUEST['grade']) : '';
		//品牌ID 
		$this->brandId = isset($_REQUEST['bid']) ? intval($_REQUEST['bid']) : 0;
		//扩展分类商品ID
		if($this->cats){
			$this->extensionGoodsId = D('GoodsCat')->getExtensionGoodsId($this->cats);
		}
		//页码
		$this->options['page'] = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
		//最小价格
		$this->options['min'] = isset($_POST['min_price']) ? ($_POST['min_price']) : $this->getParemsValue('min');
		//最大价格
		$this->options['max'] = (isset($_POST['min_price']) && ($_POST['min_price']) <= floatval($_POST['max_price'])) ? floatval($_POST['max_price']) : $this->getParemsValue('max');
		//筛选属性
		$this->options['attr'] = $this->getParemsValue('attr');
		//布局方式
		$this->options['lay'] = $this->getParemsValue('lay', 'grid');
		//显示数量
		$this->options['qty'] = $this->getParemsValue('qty', 24);
		//排序类型
		$sort = $this->getParemsValue('sort', 'add_time');
		if(in_array($sort, $this->sort)){
			$this->options['sort'] = $sort;
		}else $this->options['sort'] = 'add_time';
		//排序方式
		$order = $this->getParemsValue('order', 'desc');
		if(in_array($order, array('asc', 'desc'))){
			$this->options['order'] = $order;
		}else $this->options['order'] = 'desc';
		//推荐类型
		$this->options['recommend'] = isset($_GET['recommend']) ? trim($_GET['recommend']) : $this->getParemsValue('recommend', '');
		if(!in_array($this->options['recommend'], $this->recommend)){
			$this->options['recommend'] = '';
		}
		//搜索关键词
		$this->options['keyword'] = isset($_REQUEST['keyword']) ? urldecode(trim($_REQUEST['keyword'])) : $this->getParemsValue('keyword', '');
	}
	
	//设置筛选条件
	private function setCondition(){
		//品牌
		$this->assign('condition_brand', $this->getCategoryBrand());
		//价格
		$this->assign('condition_price', $this->getPriceGrade());
		//扩展属性
		$this->assign('filter_attr', $this->getFilterAttr());
	}
	
	//设置URL
	private function setUrl($options=array()){
		$option = array(
			'id'=>$this->catId, 
			'bid'=>$this->brandId, 
			'page'=>$this->options['page'], 
			'min'=>$this->options['min'], 
			'max'=>$this->options['max'], 
			'attr'=>$this->options['attr'],
			'lay'=>$this->options['lay'],
			'qty'=>$this->options['qty'],
			'sort'=>$this->options['sort'],
			'order'=>$this->options['order']
		);
		if(($this->options['recommend'] != '')){
			$option['recommend'] = $this->options['recommend'];
		}
		if(($this->options['keyword'] != '')){
			$option['keyword'] = urlencode($this->options['keyword']);
		}
		$option = array_merge($option, $options);
		return U('mall://List/index', $option);
	}
	
	//设置查询条件
	private function setQueryCondition(){
		$where = 'g.is_delete=0 AND g.is_on_sale=1 ';
		if($this->brandId){
			$where .= ' AND g.brand_id='.$this->brandId;			
		}
		if($this->cats){ // 商品分类与扩展分类
			$where .= ' AND ('.D('Goods')->dbIn($this->cats, 'g.cat_id').' OR '.D('Goods')->dbIn($this->extensionGoodsId, 'g.goods_id').')';
		}
		if($this->options['min']){
			$where .= ' AND g.shop_price >= '.$this->options['min'];
		}
		if($this->options['max']){
			$where .= ' AND g.shop_price <= '.$this->options['max'];
		}
		if($this->options['recommend'] != '' && in_array($this->options['recommend'], $this->recommend)){
			$where .= ' AND g.is_'.$this->options['recommend'].'=1 ';
		}
		if($this->options['keyword'] != ''){
			$where .= " AND (g.goods_name LIKE '%".$this->options['keyword']."%' OR g.goods_maidian LIKE '%".$this->options['keyword']."%' OR g.keywords LIKE '".$this->options['keyword']."')";
		}
		$ext = $this->getGoodsExt();
		if($ext){
			$where .= $ext;
		}
		$this->where = $where;
	}
	
	//取得列表产品数量
	private function getCategoryGoodsCount(){
		return M()->table(C('DB_PREFIX').'goods as g')->where($this->where)->count();
	}
	
	//取得产品列表
	private function getCategoryGoodsList(){
		$field = 'g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, ' .
                "(g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, " .
                'g.promote_start_date, g.promote_end_date, g.is_promote, g.goods_thumb, g.goods_maidian';
		$goods = M()->table(C('DB_PREFIX').'goods as g')
					->field($field)
					->where($this->where)
					->limit($this->options['qty'])
					->page($this->options['page'])
					->order('g.'.$this->options['sort'].' '.$this->options['order'])
					->findAll();
		$D = D('Goods');
		foreach ($goods AS $key=>$g){
			if($g['is_promote']){
				$price = $D->bargainPrice($g['promote_price'], $g['promote_start_date'], $g['promote_end_date']);
				$price = min(array($g['shop_price'], $g['promote_price']));
			}else{
				$price = $g['org_price'];
			}
			$goods[$key]['shop_price'] = $price;
			$goods[$key]['format_shop_price'] = $D->formatPrice($price);
			$goods[$key]['format_market_price'] = $D->formatPrice($g['market_price']);
			$goods[$key]['thumb'] = $this->getImagePath($g['goods_thumb']);
			$goods[$key]['url'] = U('mall://Product/index', array('id'=>$g['goods_id']));
		}
		return $goods;
	}
	
	//布局方式
	private function setLayout(){
		return array(
			0 => array(
				'url' => $this->setUrl(array('lay'=>'grid')),
				'name' => 'grid',
				'selected' => ($this->options['lay'] == 'grid') ? true : false
			),
			1 => array(
				'url' => $this->setUrl(array('lay'=>'list')),
				'name' => 'list',
				'selected' => ($this->options['lay'] == 'list') ? true : false
			)
		);
	}
	
	//列表显示数量
	private function setQty(){
		return array(
			0 => array(
				'url' => $this->setUrl(array('qty'=>24, 'page'=>1)),
				'text' => 24,
				'selected' => ($this->options['qty'] == 24) ? true : false
			),
			1 => array(
				'url' => $this->setUrl(array('qty'=>48, 'page'=>1)),
				'text' => 48,
				'selected' => ($this->options['qty'] == 48) ? true : false
			),
			2 => array(
				'url' => $this->setUrl(array('qty'=>96, 'page'=>1)),
				'text' => 96,
				'selected' => ($this->options['qty'] == 96) ? true : false
			)
		);
	}
	
	//排序
	private function setSortOrder(){
		$order = ($this->options['order'] == 'desc')?'asc':'desc';
		return array(
			0 => array(
				'text' => '价格',
				'url' => $this->setUrl(array('sort'=>'shop_price', 'order'=>$order)),
				'selected' => ($this->options['sort'] == 'shop_price') ? true : false
			),
			1 => array(
				'text' => '上架时间',
				'url' => $this->setUrl(array('sort'=>'add_time', 'order'=>$order)),
				'selected' => ($this->options['sort'] == 'add_time') ? true : false
			),
			2 => array(
				'text' => '更新时间',
				'url' => $this->setUrl(array('sort'=>'last_update', 'order'=>$order)),
				'selected' => ($this->options['sort'] == 'last_update') ? true : false
			),
			3 => array(
				'text' => '人气',
				'url' => $this->setUrl(array('sort'=>'click_count', 'order'=>$order)),
				'selected' => ($this->options['sort'] == 'click_count') ? true : false
			)
		);
	}
	
	//取得参数值
	private function getParemsValue($name, $default='0'){
		$value=array();
		preg_match("/$name(.*)-/isU", $this->grade.'-', $value);
		return isset($value[1]) ? $value[1] : $default;
	}
}
?>